import Vue from 'vue'
import VueRouter from 'vue-router'
import Footer from '@/components/Footer.vue'

Vue.use(VueRouter)

const routes = [
  // 首页
  {
    path: '/',
    redirect: '/homeIndex'
  },
  {
    path: '/homeIndex',
    name: 'homeIndex',
    components: {
      default: () => import('@/views/home/homeIndex.vue'),
      footer: Footer
    }
  },
  // 搜索
  {
    path: '/search',
    name: 'search',
    component: () => import('@/views/home/search.vue')
  },
  {
    path: '/searchResult',
    name: 'searchResult',
    component: () => import('@/views/home/searchResult.vue')
  },
  // 购物车
  {
    path: '/cartIndex',
    name: 'cartIndex',
    components: {
      default: () => import('@/views/cart/cartIndex.vue'),
      footer: Footer
    }
  },
  // 分类
  {
    path: '/kindIndex',
    name: 'kindIndex',
    components: {
      default: () => import('@/views/kind/kindIndex.vue'),
      footer: Footer
    }
  },
  // 用户信息
  {
    path: '/userIndex',
    name: 'userIndex',
    components: {
      default: () => import('@/views/user/userIndex.vue'),
      footer: Footer
    }
  },
  // 商品详情
  {
    path: '/detail/:proid',
    name: 'detail',
    component: () => import('@/views/detail/detail.vue')
  },
  // 登录
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login.vue')
  },
  // 注册
  {
    path: '/register',
    name: 'register',
    redirect: '/register/step1',
    component: () => import('@/views/register/register.vue'),
    children: [
      {
        path: 'step1',
        name: 'step1',
        component: () => import('@/views/register/step1.vue')
      },
      {
        path: 'step2',
        name: 'step2',
        component: () => import('@/views/register/step2.vue')
      },
      {
        path: 'step3',
        name: 'step3',
        component: () => import('@/views/register/step3.vue')
      }
    ]
  },
  // 订单
  {
    path: '/order',
    name: 'order',
    redirect: '/order/orderIndex',
    component: () => import('@/views/order/order.vue'),
    children: [
      {
        path: 'orderIndex',
        name: 'orderIndex',
        component: () => import('@/views/order/orderIndex.vue')
      },
      // 地址
      {
        path: 'addressList',
        name: 'addressList',
        component: () => import('@/views/order/addressList.vue')
      },
      {
        path: 'newAddress',
        name: 'newAddress',
        component: () => import('@/views/order/newAddress.vue')
      }
    ]
  },
  // 404
  {
    path: '*',
    component: () => import('@/views/error/notFound.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局的前置导航守卫
// 验证是否已经登录
router.beforeEach((to, from, next) => {
  // 如果页面是登录页面
  if (to.path === '/login') {
    next()
  } else {
    if (localStorage.getItem('isLogin') === 'true') {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
